package moonhy.c2dm_client;

import java.util.LinkedList;
import java.util.List;

import moonhy.c2dm_client.util.httpConnectionManager;
import moonhy.c2dm_client.util.versionCodeManager;

import org.json.JSONArray;
import org.json.JSONObject;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class SplashScreen extends Activity {
public static Thread mSplashThread;
public static boolean isRegstered = false;

Dialog dialogBack;
ProgressDialog dialogRegister;
Context context;
int appVersionOnServer;
int appVersionOnClient;


/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Splash screen view
    setContentView(R.layout.launcher);
    
    
    final SplashScreen sPlashScreen = this;
    context = this;
    

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    Log.d("C2DM", "Splash Screen: " + prefs.getAll());
	
	
	


	final String appName = context.getPackageName();
	PackageInfo pkgInfo;
	try{
		pkgInfo = context.getPackageManager().getPackageInfo(appName, 0);
		Log.e("C2DM", "Build.VERSION_CODES : " + pkgInfo.versionCode + "");
		Log.e("C2DM", "Build.VERSION_NAME : " + pkgInfo.versionName + "");
		Log.e("C2DM", "Build.VERSION.CODENAME : " + Build.VERSION.CODENAME.toString() + "");
		Log.e("C2DM", "Build.VERSION.INCREMENTAL : " + Build.VERSION.INCREMENTAL.toString() + "");
		Log.e("C2DM", "Build.VERSION.RELEASE : " + Build.VERSION.RELEASE.toString() + "");
		Log.e("C2DM", "Build.VERSION.SDK : " + Build.VERSION.SDK.toString() + "");
		Log.e("C2DM", "Build.VERSION.SDK_INT : " + Build.VERSION.SDK_INT + "");
		
		appVersionOnClient = pkgInfo.versionCode;
		
	}catch(PackageManager.NameNotFoundException e){
		Log.e("C2DM", e.getMessage());
	}
	
	appVersionOnServer = prefs.getInt("APP_VERSION_SERVER", 0);
	
	/*
	Editor edit = prefs.edit();
	edit.remove("CUR_GROUP_CODE");
	edit.remove("SAVED_MEMBER_CODE");
	edit.remove("CUR_NOTICE_CODE");
	edit.remove("CUR_VERSION_CODE");
	edit.remove("CUR_MEMBER_CODE");
	
	edit.commit();
	*/
	
    
    // The thread to wait for splash screen events
    mSplashThread =  new Thread(){
        @Override
        public void run(){
            try {
                synchronized(this){
                    // Wait given period of time or exit on touch
                	
                	/*
                	ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                    if (connectivity != null) {
                       NetworkInfo[] info = connectivity.getAllNetworkInfo();
                       if (info != null) {
                          for (int i = 0; i < info.length; i++) {
                             if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                                return true;
                             }
                          }
                       }
                    }
                    return false;
                	*/
                	
                	while(!isRegstered){
                		Log.i("C2DM", "Try to Reg...............");
                		wait(500);
                	}
                	
                	wait(700);
                }
            }catch(InterruptedException ex){                    
            
            }
            
            if(dialogRegister != null && dialogRegister.isShowing())
        		dialogRegister.dismiss();
            
            //finish();
            // Run next activity
            Intent intent = new Intent();
            intent.setClass(SplashScreen.this, TabHostActivity.class);
            startActivity(intent);
       }
    };
   
    
	
	final String googleAccount = getUsername();
	if( googleAccount == null){
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Google의 계정을 먼저 생성 하신 후 사용하시기 바랍니다.")
		       .setCancelable(false)
		       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		           @Override
				public void onClick(DialogInterface dialog, int id) {
		        	   SplashScreen.this.finish();
		           }
		       });
		AlertDialog alert = builder.create();
		alert.show();
	}else{
		String authString = prefs.getString(getApplicationContext().getString(R.string.REG_ID), "n/a");
		
		if(authString.equals("n/a")){ 
			
			Log.d("C2DM", "phone #: " + getMyPhoneNumber() + "email: " + googleAccount);
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setMessage("사용자 인증을 아직 받지 않았습니다. 지금 인증하시겠습니까?")
			       .setCancelable(false)
			       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			           @Override
					public void onClick(DialogInterface dialog, int id) {
			        	   //C2DM_ClientActivity.this.finish();
			        	   register(context, googleAccount);
			           }
			       })
			       .setNegativeButton("No", new DialogInterface.OnClickListener() {
			           @Override
					public void onClick(DialogInterface dialog, int id) {
			        	   SplashScreen.this.finish();
			           }
			       });
			       
			AlertDialog alert = builder.create();
			alert.show();
		}else{
			new initGroupInfo(this).execute();
		}
	}
}

@Override
public void onStop(){
	super.onStop();
	finish();
}

    
/**
 * Processes splash screen touch events
 */
/*
	@Override
	public boolean onTouchEvent(MotionEvent evt)
	{
	    if(evt.getAction() == MotionEvent.ACTION_DOWN)
	    {
	        synchronized(mSplashThread){
	            mSplashThread.notifyAll();
	        }
	    }
	    return true;
	}
*/

public void finalizeActivity(){
	isRegstered = true;
	mSplashThread.start();
}

public String getUsername(){
    AccountManager manager = AccountManager.get(this); 
    Account[] accounts = manager.getAccountsByType("com.google"); 
    List<String> possibleEmails = new LinkedList<String>();

    for (Account account : accounts) {
      possibleEmails.add(account.name);
    }

    if(!possibleEmails.isEmpty() && possibleEmails.get(0) != null){
        String email = possibleEmails.get(0);
        return email;
    }else
        return null;
}

public String getMyPhoneNumber(){
    return ((TelephonyManager) getSystemService(TELEPHONY_SERVICE)).getLine1Number();
}






/*
public String getMyPhoneNumber(Context context){
    return ((TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE)).getLine1Number();
}
*/

public void register(Context context, String googleAccount) {
	Log.w("C2DM", "start registration process");
	
	mSplashThread.start();
	
	Intent intent = new Intent("com.google.android.c2dm.intent.REGISTER");
	intent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
	// Sender currently not used
	//intent.putExtra("sender", googleAccount);
	intent.putExtra("sender", "zeta8302@gmail.com");
	startService(intent);
	
	
	dialogRegister = ProgressDialog.show(context, "", "사용자 인증을 시도합니다.", true);
}


public boolean isNetworkAvailable() {
	   Context context = getApplicationContext();
	   ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	   if (connectivity != null) {
	      NetworkInfo[] info = connectivity.getAllNetworkInfo();
	      if (info != null) {
	         for (int i = 0; i < info.length; i++) {
	            if (info[i].getState() == NetworkInfo.State.CONNECTED) {
	               return true;
	            }
	         }
	      }
	   }
	   return false;
	}


private class initGroupInfo extends AsyncTask<Void, Void, Void>{
	private Context context;
	private boolean mStatus = false;
	
	private initGroupInfo(Context context){
		this.context = context;
	}
	
	@Override
	protected void onPreExecute(){	
		dialogBack = ProgressDialog.show(context, "", "Loading. Please wait...", true);
	}
	
	@Override
	protected Void doInBackground(Void... unused){
		//versionCodeManager vc = new versionCodeManager(context);
		
			
        return null;
    }

    @Override
	protected void onPostExecute(Void unused){
    	dialogBack.dismiss();

		mStatus = isNetworkAvailable();
        if(!mStatus){
	        Toast.makeText(context, "3G or Wifi is not available!", Toast.LENGTH_LONG).show();
        }
        Log.d("C2DM", appVersionOnClient + " --------------- " + appVersionOnServer + " --- " + mStatus);
        
		if(mStatus && appVersionOnClient != appVersionOnServer){
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setMessage("A Newer Version of 규라인 App is Available. Want to Download it?")
			       .setCancelable(false)
			       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			           @Override
					public void onClick(DialogInterface dialog, int id) {
			        	   //C2DM_ClientActivity.this.finish();
			        	   //register(googleAccount);
			        	   
			        	   finish();
			        	   
			        	   Intent i = new Intent(Intent.ACTION_VIEW);
			        	   Uri url = Uri.parse(getString(R.string.SERVER_URL) + "package/gline.apk");
			        	   i.setData(url);
			        	   startActivity(i);
			        	   
			           }
			       })
			       .setNegativeButton("No", new DialogInterface.OnClickListener() {
			           @Override
					public void onClick(DialogInterface dialog, int id) {
			        	   //mSplashThread.start();
			        	   finalizeActivity();
			           }
			       });
			       
			AlertDialog alert = builder.create();
			alert.show();
		}else{
			//mSplashThread.start();
			finalizeActivity();
		}
		
		//Toast.makeText(this, string, Toast.LENGTH_LONG).show();
		//Log.d("C2DM", string);
    }

}

}
